<template>
  <div class="cart-box page">
    <van-nav-bar title="购物车" class="bg_grey" left-arrow @click-left="$router.go(-1)" :right-text="cartList.length > 0 ? isCartEdit ?'完成':'编辑': ''" @click-right="editCart" />
    <div class="content">
      <div class="webveiw" :style="{height:cartList.length> 2? 'auto': '100%'}">
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :style="{height:cartList.length> 2? 'auto': '100%'}">
          <van-empty description="购物车里暂无数据" image="/static/img/empty-image-default.png" v-if="cartList.length===0 " />
          <template v-for="(item,index) in cartList ">
            <div class="product-box " :key='index'>
              <div class="stroe ">
                <van-checkbox icon-size="20 " @click="check_group_all(item,index)" checked-color="#FF0034" v-model="item.checked"></van-checkbox>
                <span class="name ">{{item.shop_name}}</span>
              </div>
              <van-checkbox-group v-model="item.checkedIds " @change="check_group(item)" ref="checkGroup">
                <template v-for="(sub,_key) in item.cartList ">
                  <div class="product-info " :key="_key ">
                    <!-- <pre>{{sub}}</pre> -->
                    <van-checkbox icon-size="20 " :name="sub.cart_id " checked-color="#FF0034"></van-checkbox>
                    <div class="imgPath ">
                      <van-image :width="$tools.toPX(180) " :height="$tools.toPX(180)" fit="contain" lazy-load :src="sub.goods_img">
                        <template v-slot:loading>
                          <van-loading type="spinner " size="24 " />
                        </template>
                      </van-image>
                    </div>
                    <div class="detail ">
                      <div class="name van-multi-ellipsis--l2 ">{{sub.goods_name}}</div>
                      <div class="spec ">{{sub.specItemList | formatSpec}}</div>
                      <div class="price-num ">
                        <div class="m-price ">{{sub.spec_price}}
                        </div>
                        <van-stepper class="stepper " @blur="changeCartNum(sub)" @plus="changeCartNum(sub,'plus')" @minus="changeCartNum(sub, 'minus')" :input-width="$tools.toPX(77) + 'px' " :button-size="$tools.toPX(54) + 'px'" v-model="sub.num" min="1" :max="sub.spec_stock+1" />
                      </div>
                    </div>
                  </div>
                </template>
              </van-checkbox-group>
            </div>
          </template>
        </van-pull-refresh>
      </div>
    </div>
    <div class="submit-bar " v-if="cartList.length> 0">
      <van-checkbox icon-size="20" checked-color="#FF0034" @click.native="check_all" v-model="isAllChecked">
        <span class="all">全选</span>
      </van-checkbox>
      <div class="total_btn">
        <span class="del" v-if="isCartEdit" @click="del_cart()">删除</span>
        <template v-else>
          <div class="total">
            合计:
            <span class="m-price">{{cartData.money | toFixed}}</span>
          </div>
          <van-button class="btn" round type="info" @click.native="settlement" color="#FF0034">结算({{cartData.num}})</van-button>
        </template>
      </div>
    </div>
    <tab-bar v-model="isActive"></tab-bar>
  </div>
</template>
<script>
import mixins from '@/utils/mixins';
export default {
  name: 'cart',
  data () {
    return {
      isAllChecked: false,
      isActive: 3,
      isCartEdit: false,
      apiType: 'cart',
      apiUrl: 'list',
      ids: [], // 购物车ids
      cartList: [],
      idsArr: [], // 选中ID集合
      cartData: {
        num: 0,
        money: 0
      }
    };
  },
  mixins: [mixins],
  created () {
    this.getCartList();
  },
  methods: {
    getCartList () {
      this.getList(this.apiUrl, true, (dataList) => {
        this.cartList = dataList.map((item) => {
          item.checked = false; // 添加选中值
          item.cartList.map((res) => {
            res.checkedIds = [];
          });
          return item;
        });
      });
    },
    // 编辑购物车
    editCart () {
      this.isCartEdit = !this.isCartEdit;
    },
    // 单个店铺全选
    check_all () {
      this.isAllChecked = !this.isAllChecked;
      this.cartList.map((res, index) => {
        res.checked = !res.checked;
        var checkGroup = this.$refs['checkGroup'][index];
        checkGroup.toggleAll(this.isAllChecked);
      });
      // this.accutateNum();// 获取
    },
    // 单个店铺全选
    check_group_all (item, index) {
      var checkGroup = this.$refs['checkGroup'] && this.$refs['checkGroup'][index];
      checkGroup.toggleAll(item.checked);
      this.isAllChecked = this.cartList.every(i => i.checked);
    },
    // 单个商品选中
    check_group (item) {
      item.checked = item.checkedIds.length === item.cartList.length;
      this.accutateNum();// 获取
      this.isAllChecked = this.cartList.every(i => i.checked);
    },
    // 删除商品
    del_cart (id) {
      var res = false;
      // 判断是否有勾选项
      res = this.cartList.some(item => {
        return item.checkedIds && item.checkedIds.length > 0;
      });
      if (res) {
        // 获取选中的商品的id
        this.cartList.forEach(item => {
          item.checkedIds && item.checkedIds.forEach(j => {
            this.idsArr.push(j);
          });
        });
        this.$dialog.confirm({
          title: '温馨提示',
          message: '确认删除这' + this.idsArr.length + '商品吗?',
          beforeClose: (action, done) => {
            if (action === 'confirm') {
              setTimeout(() => {
                console.log(this.idsArr);
                this.$API.cart.delete({ ids: this.idsArr.join(',') }).then(res => {
                  if (!res.code) {
                    this.isAllChecked = false;
                    this.getCartList(); // 更新购物车
                    this.idsArr = []; // 清空数组
                    this.$toast('删除成功');
                    done();
                  }
                });
                done();
              }, 1000);
            } else {
              done();
            }
          }
        });
      } else {
        this.$toast('您尚未勾选商品');
      }
    },
    deleteGoodsToCart () {
      let ids = [];
      for (var i of this.idsArr) {
        ids.push(i.id);
      }
      try {
        // this.changeCartNum();
      } catch (err) {
        throw new Error(err);
      }
    },
    // 购物车数量操作
    changeCartNum (data, type) {
      console.log(data.num, data.spec_stock);
      if (type === 'plus') {
        data.num += 1;
      } else if (type === 'minus') {
        data.num -= 1;
      }
      this.$API.cart.cartNum({ id: data.cart_id, num: data.num }).then(res => {
        if (res.code) {
          this.$toast('修改失败');
        } else {
          this.accutateNum();
        }
      });
    },
    // 获取结算金额
    accutateNum () {
      let num = 0;
      let groupNum = [];
      let total = 0;
      this.cartList.forEach(item => {
        if (item.checkedIds && item.checkedIds.length > 0) {
          item.checkedIds.forEach(j => {
            num += 1;
            var cartItem = item.cartList.find(i => j === i.cart_id);
            groupNum.push(cartItem);
          });
        }
      });
      // 计算总数
      groupNum.forEach(item => {
        total += item.num * item.spec_price;
      });
      this.cartData.num = num;
      this.cartData.money = total;
    },
    // 立即结算
    settlement () {
      let allIds = [];
      console.log(this.cartList);
      this.cartList.forEach(item => {
        if (item.checkedIds && item.checkedIds.length > 0) {
          item.checkedIds.forEach((j, index) => {
            allIds.push(j);
          });
        }
      });
      let val = allIds.length > 0 ? allIds && allIds.reduce((total, currentValue, currentIndex, arr) => {
        return total + currentValue;
      }) : 0;
      if (val === 0) { // 全部未勾选
        this.$toast('尚未勾选商品');
      } else { // 有勾选项
        this.$router.push({ 'path': '/order/confirm', query: { ids: allIds.join(',') } });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.cart-box {
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    overflow: auto;
    padding-bottom: 20px;
    .nodata {
      background-color: #fff;
    }
  }
  .submit-bar {
    background-color: #fff;
    padding: 15px 10px 15px 40px;
    display: flex;
    justify-content: space-between;
    .all {
      font-size: 30px;
      position: relative;
      top: 1px;
    }
    .total_btn {
      display: flex;
      align-items: center;
      .total {
        font-size: 28px;
        .m-price {
          font-size: 32px;
          color: #ff0034;
          margin-right: 20px;
          font-weight: 800;
        }
      }
      .del {
        height: 70px;
        padding: 0 40px;
        background-color: #fff;
        text-align: center;
        font-size: 30px;
        line-height: 68px;
        border: 1px solid #bbb; /*no*/
        border-radius: 40px;
      }
      .btn {
        padding: 0 40px;
        height: 80px;
        line-height: 80px;
      }
    }
  }
}
</style>
